<?php
/**
 * Imagick.php
 * 
 * @category   Naneau
 * @package    Naneau_Image
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 * @version    0.1
 */

/**
 * Naneau_Image_Adapter_Imagick
 * 
 * image adapter for imagick
 *
 * @category   Naneau
 * @package    Naneau_Image
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 */
class Naneau_Image_Adapter_Imagick {
    protected function _generateThumb($x, $y) {
        if(!in_array('imagick', get_loaded_extensions())) {
            throw new Exception("The Image Magick _PECL EXTENSION_ Must Be Installed To Generate Thumbnails!");
        }

        $imagePath = $this->contentPath;
        clearstatcache();
        if(!is_dir($imagePath) || !is_writable($imagePath)) {
            throw new Exception("The target directory: ". $imagePath .' is not writable or is non-existant');
        }
        //Here we know even if the sample dir doesnt exist we can make it
        $thumbPath = $imagePath .'/'. $x .'x'. $y;
        if(!is_dir($thumbPath)) {
            mkdir($thumbPath, 0775);
        }
        if(is_writable($thumbPath)) {
            //create thumb and save
            $originalFile = $this->contentPath .'/originals/'. $this->imageId;
            $targetFile = $thumbPath .'/'. $this->imageId;
            if(is_readable($originalFile)) {
                $handle = imagick_readimage($originalFile);

                if(!is_resource($handle)) {
                    throw new Exception("Image Magick could not parse the original file for resampling. File: ". $originalFile);
                }

                //yes i realise this will convert pjpegs to jpeg
                if(imagick_getmimetype($handle) != 'image/jpeg') {
                    if(!imagick_convert($handle, 'JPG')) {
                        throw new Exception("Image Magick conversion failed to convert type. Reason: ". imagick_failedreason($handle) . ". Description: ". imagick_faileddescription($handle));
                    }
                }

                $this->mimeType = imagick_getmimetype($handle);

                if(!imagick_resize( $handle, $x, $y, IMAGICK_FILTER_UNKNOWN, 1)) {
                    throw new Exception("Image Magick conversion failed to resize. Reason: ". imagick_failedreason($handle) . ". Description: ". imagick_faileddescription($handle));
                }
                

                if(!imagick_writeimage($handle, $targetFile) || !is_readable($targetFile)) {
                    throw new Exception("Image Magick conversion failed to save file. Reason: ". imagick_failedreason($handle) . ". Description: ". imagick_faileddescription($handle));
                }

                unset($handle);

                // Watermark image if the thumbnail is high res

                if($x == 640 || $y == 480) {

                    if(is_readable($this->waterMarkFile)) {
                        $watermark = imagecreatefrompng($this->waterMarkFile);

                        $image = imagecreatefromjpeg($targetFile);

                        $image_width = imagesx($image);
                        $image_height = imagesy($image);
                        $watermark_width = imagesx($watermark);
                        $watermark_height = imagesy($watermark);

                        $wm_dest = imagecreatetruecolor($image_width, $image_height);
                        imagealphablending($wm_dest, false);
                        imagecopyresampled($wm_dest, $watermark, 0,0,0,0, $image_width, $image_height, $watermark_width, $watermark_height);
                        imagesavealpha($wm_dest, true);

                        imagecopy($image, $wm_dest, 0, 0, 0, 0, $image_width, $image_height);
                        imagejpeg($image, $targetFile, 100);

                        imagedestroy($image);
                        imagedestroy($watermark);
                    }
                }

                $stream = fopen($targetFile, 'r');

                if(is_resource($stream) && get_resource_type($stream) == 'stream') {
                    $this->fileName = $targetFile;
                    $this->contentLength = filesize($targetFile);
                    return $stream;
                } else {
                    throw new Exception("Could not open the thumbnail for reading. File: ". $targetFile);
                }
            } else {
                throw new Exception("There was a problem locating the original image data to create a thumbnail from.");
            }
        } else {
            throw new Exception("There was a problem creating the directory for the thumbnail");
        }
    }
}